from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status
from .response import ApiResponse, ErrorCode
import logging

logger = logging.getLogger(__name__)

def custom_exception_handler(exc, context):
    """自定义异常处理器"""
    # 调用DRF默认的异常处理器
    response = exception_handler(exc, context)
    
    if response is not None:
        # 根据异常类型返回统一格式
        if response.status_code == status.HTTP_404_NOT_FOUND:
            return ApiResponse.error(
                "资源不存在",
                ErrorCode.NOT_FOUND_ERROR,
                response.data,
                status.HTTP_404_NOT_FOUND
            )
        elif response.status_code == status.HTTP_401_UNAUTHORIZED:
            return ApiResponse.error(
                "未授权访问",
                ErrorCode.AUTHENTICATION_ERROR,
                response.data,
                status.HTTP_401_UNAUTHORIZED
            )
        elif response.status_code == status.HTTP_403_FORBIDDEN:
            return ApiResponse.error(
                "权限不足",
                ErrorCode.PERMISSION_ERROR,
                response.data,
                status.HTTP_403_FORBIDDEN
            )
        elif response.status_code == status.HTTP_400_BAD_REQUEST:
            return ApiResponse.error(
                "请求参数错误",
                ErrorCode.VALIDATION_ERROR,
                response.data,
                status.HTTP_400_BAD_REQUEST
            )
        else:
            return ApiResponse.error(
                "服务器错误",
                ErrorCode.GENERAL_ERROR,
                response.data,
                response.status_code
            )
    
    # 未处理的异常
    logger.error(f"Unhandled exception: {exc}")
    return ApiResponse.error(
        "服务器内部错误",
        ErrorCode.GENERAL_ERROR,
        http_status=status.HTTP_500_INTERNAL_SERVER_ERROR
    )